package com.leonzx.base.config.datasource;

import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.After;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.stereotype.Component;

import java.lang.reflect.Method;

/**
 * Created by liang on 2018/3/28.
 */
@Aspect
@Component
public class DynamicDataSourceAspect {

    /**
     * 根据DS注解切换数据源逻辑
     *
     * @param joinPoint
     */
    @Before("@annotation(DS)")
    public void beforeSwitchDS(JoinPoint joinPoint) {
        //获取当前访问的class
        Class<?> className = joinPoint.getTarget().getClass();
        //获取访问的方法名称
        String methodName = joinPoint.getSignature().getName();
        //得到方法参数的类型
        Class[] argClass = ((MethodSignature) joinPoint.getSignature()).getParameterTypes();
        String dataSource = DataSourceContextHolder.DEFAULT_DS;
        try {
            // 得到访问的方法对象
            Method method = className.getMethod(methodName, argClass);
            DS annotation = method.getAnnotation(DS.class);
            dataSource = annotation.value();
        } catch (Exception e) {
            e.printStackTrace();
        }
        // 切换数据源
        DataSourceContextHolder.setDB(dataSource);
    }

    /**
     * 清除数据源
     *
     * @param point
     */
    @After("@annotation(DS)")
    public void afterSwitchDS(JoinPoint point){
        DataSourceContextHolder.clearDB();
    }
}
